<template>
  <div class="edite">
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rules"
      :label-width="100"
    >
      <!-- 配置层级 -->
      <Form-item prop="scopeLevel" :label="$t('module.configManage.configHierarchy')">
        <Select
          v-model="modelForm.scopeLevel"
          :disabled="isShowOverall"
          @on-change="onLevelChange"
          :placeholder="$t('module.configManage.enterconfigHierarchy')"
        >
          <Option
            v-for="level in configLevelList"
            :value="level.key"
            :key="level.key"
          >{{ level.value }}</Option>
        </Select>
      </Form-item>
      <!-- 角色/用户 -->
      <Form-item prop="scopeContextName" :label="hierarchyName" v-if="isContextShow">
        <Row :gutter="32">
          <Col span="20">
            <Input
              v-model="modelForm.scopeContextName"
              :placeholder="$t('module.configManage.enterLevelContext')"
              readonly
              disabled
              style="width: 356px"
            ></Input>
          </Col>
          <Col span="4" class="textLeft">
            <RPButton
              optType="reset"
              :text="$t('module.configManage.select')"
              @click="selectContext"
            />
          </Col>
        </Row>
      </Form-item>
      <!-- 租户 -->
      <Form-item
        v-if="isShowTanent"
        prop="scopeContextName"
        :label="$t('module.configManage.tenement')"
      >
        <Input
          type="text"
          :maxlength="30"
          v-model.trim="modelForm.scopeContextName"
          disabled
        />
      </Form-item>
      <!-- 参数值 -->
      <Form-item prop="value" :label="$t('module.configManage.parameter')">
        <Select
          v-model="modelForm.value"
          :placeholder="$t('module.configManage.selectparameter')"
          v-if="parentItem.valueSetCode"
          :transfer="true"
          @on-change="selectparameter"
        >
          <Option
            v-for="item in parameterList"
            :title="item.vsiValue"
            :value="item.vsiKey"
            :key="item.vsiKey"
          >{{ item.vsiKey }}</Option>
        </Select>
        <Input
          v-model="modelForm.value"
          :placeholder="$t('module.configManage.enterparameter')"
          v-else
        ></Input>
      </Form-item>
      <!-- 状态 -->
      <Row :gutter="32" class="code-row-bg">
        <Col span="12" style="border: none">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="modelForm.enabled">
              <Radio :label="1">{{ $t("common.enable") }}</Radio>
              <!-- <Radio :label="0">{{ $t("common.disable") }}</Radio> -->
              <Radio
                :label="0"
                :disabled="this.scopeLevel == 0 || (this.scopeLevel == 1 && !this.isRIPPLES && parentItem.tenantCode == this.tenantCode)"
              >{{ $t("common.disable") }}</Radio>
            </RadioGroup>
          </Form-item>
        </Col>
      </Row>
      <!-- 描述 -->
      <Form-item :label="$t('module.configManage.description')">
        <Input
          v-model="modelForm.description"
          type="textarea"
          :rows="4"
          placeholder
          :maxlength="200"
        />
      </Form-item>
    </Form>
  </div>
</template>
<script>
import { addConfigValue, updateConfigValue } from "@/api/configApi.js";
import valueSetAPI from "@/api/valueSetAPI.js";
import locales from "./locales.js";
import SelectTenant from "./SelectTenant.vue";
import SelectRole from "./SelectRole.vue";
import SelectUser from "./SelectUser.vue";
import { CONFIG_LEVEL_GLOBAL, CONFIG_LEVEL_TENANT, CONFIG_LEVEL_ROLE, CONFIG_LEVEL_USER } from "./const.js";

export default {
  name: "editeitemconfig",
  mixins: [locales],
  props: {
    tenantCode: {
      type: String,
      default: ""
    },
    tenantName: {
      type: String,
      default: ""
    },
    configItemId: {
      type: String,
      default: ""
    },
    allItems: Array,
    valueId: String,
    // owners: Array,
    configValue: {
      type: Object,
      default: () => ({})
    },
    parentItem: {
      type: Object,
      default: () => ({})
    },
    // isRIPPLES: {
    //   type: Boolean,
    //   default: () => ({})
    // },
    configInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    scopeLevel: {
      type: Number
    },
    scopeLevelNum: {
      type: Number
    }
  },
  data() {
    // 配置层级
    const validateScopeLevel = (rule, value, callback) => {
      if (value === "" || value === undefined || value === null) {
        callback(new Error(this.$t("module.configManage.enterconfigHierarchy")));
      }
      callback();
    };
    // 租户/角色/用户
    const validateScopeContext = (rule, value, callback) => {
      if (value === "" || value === undefined || value === null) {
        callback(new Error(this.$t("module.configManage.enterLevelContext")));
      }
      callback();
    };
    // 参数值
    const validateOwner = (rule, value, callback) => {
      if (value === "" || value === undefined || value === null) {
        this.parentItem.valueSetCode
          ? callback(new Error(this.$t("module.configManage.selectparameter")))
          : callback(new Error(this.$t("module.configManage.enterparameter")));
      }
      callback();
    };

    return {
      modelForm: {
        tenantCode: this.tenantCode,
        // configId: this.valueId,
        configItemId: this.configItemId,
        itemCode: this.parentItem.code, //配置项得编码
        scopeLevel: null, //配置层级
        scopeContext: null, //配置上下文
        scopeContextName: null, //租户/角色/用户
        value: null, //参数值
        enabled: 1, //状态
        description: null, //描述
        valueSetItemId: null, //指定了值集后值集中值的id
        ...this.configValue
      },
      configLevelList: [],
      parameterList: [],
      pageObj: null,
      rules: {
        //配置层级
        scopeLevel: [
          {
            required: true,
            validator: validateScopeLevel,
            trigger: "change"
          }
        ],
        //租户/角色/用户
        scopeContextName: [
          {
            required: true,
            validator: validateScopeContext,
            trigger: "change"
          }
        ],
        // levelContext: [
        //   {
        //     required: true,
        //     message: this.$t("module.configManage.enterLevelContext"),
        //     trigger: "blur"
        //   }
        // ],
        // 参数值
        value: [{ required: true, validator: validateOwner, trigger: "change" }]
      },
      hierarchyName: null,
      isShowTanent: false,
      isShowOverall: false,
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    isContextShow() {
      let isShow = false;
      //  if (this.modelForm.scopeLevel == CONFIG_LEVEL_GLOBAL) {
      //   isShow = false;
      // }
      if (this.modelForm.scopeLevel == CONFIG_LEVEL_TENANT) {
        // if (this.isRIPPLES) {
        //   isShow = true;
        //   this.pageObj = SelectTenant;
        // } else {
        //   isShow = false;
        //   this.modelForm.scopeContext = this.tenantCode;
        // }
        this.isShowTanent = true;
        isShow = false;
        this.modelForm.scopeContextName = this.tenantName;
      } else if (this.modelForm.scopeLevel == CONFIG_LEVEL_ROLE) {
        this.hierarchyName = this.$t("module.configManage.role");
        isShow = true;
        this.isShowTanent = false;
        this.pageObj = SelectRole;
      } else if (this.modelForm.scopeLevel == CONFIG_LEVEL_USER) {
        this.hierarchyName = this.$t("module.configManage.user");
        isShow = true;
        this.isShowTanent = false;
        this.pageObj = SelectUser;
      }
      return isShow;
    }
  },
  created() {
    this.isRIPPLES = this.tenantCode == window.RPConfig.rootTenantCode;
    this.init();
    if (this.configValue.id) {
      this.$emit("SetTitle", this.$t("module.configManage.editConfigValue"));
    } else {
      this.$emit("SetTitle", this.$t("module.configManage.createConfigValue"));
    }

    this.$emit("SetPageWidth", 600);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    selectparameter(value) {
      this.parameterList.map(item => {
        if (item.vsiKey == value) {
          this.modelForm.valueSetItemId = item.id;
        }
      });
    },
    init() {
      // 初始化配置层级
      this.initConfigLevel();
      // 初始化参数值
      this.initParameter();
    },
    // 初始化配置层级
    initConfigLevel() {
      // 编辑时不能修改 配置层级
      if (this.configValue.id) {
        this.isShowOverall = true;
      }
      let list = null;
      if (this.tenantCode == window.RPConfig.rootTenantCode && this.configValue.id) {
        // 编辑时，因为新增的时候tenantName为空
        this.modelForm.value = this.configValue.value;
        list = [
          {
            key: CONFIG_LEVEL_GLOBAL,
            value: this.$t("module.configManage.platformDefault")
          },
          {
            key: CONFIG_LEVEL_TENANT,
            value: this.$t("module.configManage.tenement")
          },
          {
            key: CONFIG_LEVEL_ROLE,
            value: this.$t("module.configManage.role")
          },
          {
            key: CONFIG_LEVEL_USER,
            value: this.$t("module.configManage.user")
          }
        ];
      } else {
        // 新增时
        if (this.configInfo.tenantCode == window.RPConfig.rootTenantCode) {
          list = [
            {
              key: CONFIG_LEVEL_TENANT,
              value: this.$t("module.configManage.tenement")
            },
            {
              key: CONFIG_LEVEL_ROLE,
              value: this.$t("module.configManage.role")
            },
            {
              key: CONFIG_LEVEL_USER,
              value: this.$t("module.configManage.user")
            }
          ];
          if (this.scopeLevelNum == 1) {
            list.splice(0, 1);
          }
        } else {
          list = [
            {
              key: CONFIG_LEVEL_ROLE,
              value: this.$t("module.configManage.role")
            },
            {
              key: CONFIG_LEVEL_USER,
              value: this.$t("module.configManage.user")
            }
          ];
        }
      }
      if (this.scopeLevel == 1) {
        list = [
          {
            key: CONFIG_LEVEL_TENANT,
            value: this.$t("module.configManage.tenement")
          }
        ];
      }

      valueSetAPI.getValueSetByCode("SYS_PROFILE_LEVEL").then(data => {
        list.forEach(level => {
          let valueSet = data.find(valueSetItem => {
            return valueSetItem.vsiKey == level.key;
          });
          if (valueSet) {
            level.value = valueSet.vsiValue;
          }
        });
        this.configLevelList = list;
      });
    },
    // 初始化参数值
    initParameter() {
      // 如果有值来源获取值集
      if (this.parentItem.valueSetCode) {
        valueSetAPI.getValueSetByCode(this.parentItem.valueSetCode).then(data => {
          this.parameterList = data;
        });
      }
    },
    // 配置层级切换时
    onLevelChange(val) {
      this.modelForm.scopeContext = null;
      this.modelForm.scopeContextName = null;
    },
    // 选择层级上下文
    selectContext() {
      new this.$pageModal(
        this.pageObj,
        {
          props: {
            value: this.modelForm.scopeLevel - 0
          }
        },
        data => {
          if (data) {
            if (this.modelForm.scopeLevel == CONFIG_LEVEL_TENANT) {
              this.modelForm.scopeContext = data.id;
              this.modelForm.scopeContextName = data.tenantName;
            } else if (this.modelForm.scopeLevel == CONFIG_LEVEL_ROLE) {
              this.modelForm.scopeContext = data.id;
              this.modelForm.scopeContextName = data.roleName;
            } else if (this.modelForm.scopeLevel == CONFIG_LEVEL_USER) {
              this.modelForm.scopeContext = data.id;
              this.modelForm.scopeContextName = data.userName;
            }
          }
        }
      );
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.valueId) {
            updateConfigValue(this.modelForm)
              .then(res => {
                if (res) {
                  const content = this.$t("common.updateSuccess");
                  this.$message.success({
                    content: content,
                    duration: 3
                  });
                  this.$emit("Close", true);
                }
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          } else {
            // 添加配置项
            addConfigValue(this.modelForm)
              .then(res => {
                if (res) {
                  const content = this.$t("module.receiptSequence.createSuccess");
                  this.$message.success({
                    content: content,
                    duration: 3
                  });
                  this.$emit("Close", true);
                }
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          }
        } else {
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.edite {
  .textLeft {
    text-align: right;
    button {
      padding: 3px 20px;
    }
  }
}
</style>
